package com.sh4.util;

import org.codehaus.jackson.map.ObjectMapper;

import net.sf.json.JSONObject;

/**
 * 生成json数据和解析json数据
 * 
 * @author huxh
 *
 */
public class JackJsonUtils {
	
	
	static ObjectMapper objectMapper;
	

	/**
	 * 解析json
	 *  String JSON ==> T
	 * @param content
	 * @param valueType
	 * @return
	 */
	public static <T> T fromJson(String content, Class<T> valueType) {
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}
		try {
			return objectMapper.readValue(content, valueType);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 生成json
	 * 
	 * @param object
	 * @return
	 */
	public static String toJson(Object object) {
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}
		try {
			return objectMapper.writeValueAsString(object);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 生成json2
	 * 
	 * @param object
	 * @return
	 */
	public static JSONObject toJson2(String object) {
		try {
			return JSONObject.fromObject(object);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
